import { observable, action } from 'mobx';
import { hashHistory } from 'react-router';
import { message } from 'antd'
import Ajax from '../lib/Ajax';
import LanguageStore from './languageStore';

export default class AppStore {
  @observable commonData = {};
  @observable userData = {};
  @observable isSignined = false;
  @observable imgBaseUrl = '';
  @observable isLogined = false;

  constructor(initState) {
    this.languageStore = new LanguageStore();

    this.fetchCommonData();
    this.fetchUserData();
  }

  @action signin(b){
    this.isSignined = b
  }

  @action saveLoginDto(dto){
    this.userData = dto;
    this.isLogined = true;
  }

  getNameById(type, code){
    const find = _.find(this.commonData[type], item=>item.code == code);
    return find?find.mean:""
  }

  fetchCommonData(){
    var self = this;
    Ajax({
      url: '/common/data',
      success: function(result){
        self.commonData = result;
        self.imgBaseUrl = result.imageHost;
      },
      error: function(error){
        Toast.info(error||'请求失败');
      }
    });
  }

  fetchUserData(){
    var self = this;
    Ajax({
      url: '/user/get',
      success: function(result){
        self.userData = result;
        self.isLogined = true;
      },
      error: function(error){
        message.info(error||'请求失败');
      }
    });
  }

  checkIsLogined(){
    if(this.isLogined){
      return true
    }else{
      hashHistory.push('/login');
    }
  }
}
